#!/usr/bin/env python
# coding: utf-8
"""
@Author : ZhaoBin
@Date   : 2018-11-29 11:07:07
@Last Modified by   : ZhaoBin
@Last Modified time : 2018-12-11 09:56:07
"""

import re
from time import sleep

import requests
from Base import Base
import settings


class Australia(Base):
    """ 澳大利亚签证 """

    def __init__(self, no_win=True, no_img=False, logger=None, info=None):
        super().__init__(no_win=no_win, no_img=no_img)
        self.logger = logger if logger else settings.get_log("default_log")
        self.email = settings.EMAIL_NAME
        self.email_pwd = settings.EMAIL_PASSWORD
        self.password = settings.VISA_PASSWORD

        self.info = info if info else []

        self.pages = {
            "2": self.page_2,
            "3": self.page_3,
        }

    # 注册
    @property
    def register(self):
        self.logger.info("\n\nAt Register:\n")
        self.get_driver()
        self.register_page_one()
        result = self.register_page_two()
        return result

    # 激活
    def active(self, title="Confirm your ImmiAccount email address"):
        self.logger.info("\n\nAt Active:\n")
        if not hasattr(self, "driver"):
            self.get_driver()
        self.mailing_list(self.email, self.email_pwd, title)

    # 申请签证
    def visa(self):
        self.logger.info("\n\nAt Visa:\n")
        if not hasattr(self, "driver"):
            self.get_driver()
        self.login()
        self.new_application()
        # self.old_application() if self.login() else self.new_application()
        # self.Wait(xpath='//span[text()="Next"]')
        while True:
            page = self.get_page()
            if page:
                self.pages[page]()
            else:
                break

    # 注册 page-1
    def register_page_one(self, group=False):
        self.driver.get(settings.REGISTER_URL)
        self.Wait("_2b0e0a0a1a0b")
        # if group:
        #     组织
        #     self.Wait("_2b0e0a0a1a1b")
        #     self.Wait("_2b0e0a0a2a0b0_7")
        #     self.Wait("_2b0e0a0a2a0b0_3")
        #     self.Wait("_2b0e0a0a2a0b0_2")
        #     self.Wait("_2b0e0a0a2a0b0_1")
        # LEGENDcom（需要购买/加入年度订阅）
        # if 0:
        #     self.Wait("_2b0e0a0a3a0b0_7")
        # 姓氏
        self.Wait("_2b0e0a0a5b", "chen")
        # 电话
        self.Wait("_2b0e0a0a5d", "18801235888")
        # 邮箱
        self.Wait("_2b0e0a0a5f", self.email)
        # 确认邮箱
        self.Wait("_2b0e0a0a5g", self.email)
        self.Wait(css="button[name='continue']")

    # 注册 page-2
    def register_page_two(self):
        # 密码
        self.Wait("_2b0e0a0b1", self.password)
        # 确认密码
        self.Wait("_2b0e0a0b3", self.password)
        # 问题1 What is the name of your favourite teacher?
        self.choiceSelect(self.Wait("_2b0e0a0b5a-r0-_0a0b0", text=settings.NC), "1")
        self.Wait("_2b0e0a0b5a-r0-_0a2b", "AAA")
        # 问题2 Where were you born?
        self.choiceSelect(self.Wait("_2b0e0a0b5a-r1-_0a0b0", text=settings.NC), "2")
        self.Wait("_2b0e0a0b5a-r1-_0a2b", "BBB")
        # 问题3 What was your first job?
        self.choiceSelect(self.Wait("_2b0e0a0b5a-r2-_0a0b0", text=settings.NC), "3")
        self.Wait("_2b0e0a0b5a-r2-_0a2b", "CCC")

        self.Wait("_2b0e0a0b8")
        self.Wait(css=".field.nolabel > div > div > div")
        self.Wait(css=".buttonBarLR button:last-child")

        if "Your account has successfully been created." in self.driver.page_source:
            self.logger.info("register successful")
            return 1
        return 0

    # 邮箱激活 - 登陆-选择文件夹
    def mailing_list(self, title=None):
        self.driver.get("http://mail.163.com/index_alternate.htm")
        try:
            # == 使用 6.0简约版 登陆
            self.Wait("styleConf")
            self.Wait("styleconf6")
            # =====================
            self.logger.info("输入用户名")
            self.Wait("idInput", self.email)
            self.logger.info("输入密码")
            self.Wait("pwdInput", self.email_pwd)
            self.logger.info("点击登录")
            self.Wait("loginBtn")
            self.logger.info("点击收件箱")
            self.Wait(xpath='//*[@title="收件箱"]')
            sleep(1)
            self.Wait(xpath='//*[contains(text(), "全部设为已读")]', text=settings.NC)
            if title not in self.driver.page_source:
                self.logger.info("点击其他邮件")
                self.Wait(xpath='//span[contains(text(), "显示更多")]', text=settings.NC)
                more = self.driver.find_elements_by_xpath('//span[contains(text(), "显示更多")]')
                more[1].click()
                self.logger.info("点击垃圾箱")
                self.Wait(xpath='//span[contains(text(), "垃圾邮件")]')
            if title not in self.driver.page_source:
                self.logger.info("无邮件")
                return 0
            self.logger.info(f'点击 {title} 邮件')
            self.Wait(xpath=f'//span[contains(text(), "{title}")]')

            sleep(0.5)
            f2 = self.Wait(css="div.rd-content > iframe")
            self.driver.switch_to.frame(f2)
            return 1 if self.australia_active else 0
        except Exception as e:
            self.logger.error('-' * 20)
            self.logger.error("激活失败")
            return 0

    # 邮箱激活 - 获取激活连接
    @property
    def australia_active(self):
        for _ in range(50):
            if "online.immi.gov.au" in self.driver.page_source:
                break
            sleep(0.1)
        self.logger.info('获取链接地址')
        reg = r"https://online\.immi\.gov\.au.*?[\s\n\"'<]"
        em_url = re.findall(reg, self.driver.page_source)[0].strip(r"\"'<\s")
        # em_url = self.Wait(tag_name="a", text=settings.NC).get_attribute("href")
        self.logger.info(em_url)
        res = requests.get(em_url)
        if "Success" in res.text:
            self.logger.info("激活成功")
            return 1
        self.logger.info("激活失败")
        return 0

    # 位置
    def get_page(self):
        label = self.Waits(css=".wc-cell>.wc-label")
        return label[0].text.split("/")[0] if label else None

    # 登陆
    def login(self):
        self.driver.get(settings.LOGIN_URL)
        self.Wait("username", self.email)
        self.Wait("password", "QWEqwe123")
        self.Wait(css=".buttonBarLR> button[name='login']")
        # 点击继续
        self.logger.info("点击继续")
        self.Wait(css="button")
        tablist = self.Wait(css='[role="tablist"]', text=settings.NC)
        if len(tablist.find_elements("tag name", "div")) > 0:
            return 1
        return 0

    # 旧记录
    def old_application(self):
        app = self.Wait("MyAppsResultTab_0", settings.NC)
        app.click() if app.get_attribute("aria-expanded") == "false" else ""
        self.Wait("actionPanel_0_0")
        self.Wait(css=".wc-east > button")

    # 新增记录
    def new_application(self):
        # 新增申请
        self.logger.info("新增申请")
        self.Wait("btn_newapp")
        # 选择 Visitor Visa (600)
        sleep(1)
        self.logger.info("选择 Visitor Visa (600)")
        # self.Wait("mainpanel_parentSection_1b0a0bd_o")
        self.Wait("mainpanel_parentSection_1b0a0bd_o")
        sleep(2)
        elem = self.Wait("mainpanel_parentSection_1b0a0bd-content", settings.NC)
        if elem.get_attribute("aria-expanded") == "false":
            self.Wait("mainpanel_parentSection_1b0a0bd_o")
        self.Wait("mainpanel_parentSection_1b0a0bd1c", timeout=10)
        # page-1 同意
        self.logger.info("page-1 同意")
        self.Wait(css=".ELP-F2130 input")
        self.next_page

    # -------------------------------------------------- #
    # -------------------------------------------------- #
    # -------------------------------------------------- #
    # 第二页
    def page_2(self):
        # 是否在澳洲之外
        self.logger.info("是否在澳洲之外")
        self.Wait(css='input[type="radio"]', text=settings.NC)
        radios = self.driver.find_elements_by_css_selector('input[type="radio"]')
        if "是":
            radios[0].click()
            # 选择中国-公民
            self.logger.info("选择中国-公民")
            self.Wait(css="select", text=settings.NC)
            selects = self.driver.find_elements_by_css_selector("select")
            self.choiceSelect(selects[0], "PRCH")
            sleep(1)
            self.choiceSelect(selects[1], "3")
            if "3" != "1":  # 1, 2, 3, 4, 5, 7, 99
                textareas = self.Waits(tag_name="textarea")
                textareas[0].send_keys("aa")
            # 选择申请人申请的类型
            self.logger.info("选择申请人申请的类型")
            self.Wait(css=f"input[value='{29}']")
            sleep(2)
            # 申请人类型延伸
            radios = self.Waits(css=".wc-option>input")
            if 29 or 31:
                if "N":
                    radios[27].click()
                elif "N":
                    radios[26].click()
            elif 61:
                if "Y":
                    radios[18].click()
                elif "N":
                    radios[19].click()
                self.Wait(css='.ELP-F1902>input[type="text"]', text="aa")

            # 列出访问澳大利亚的所有理由
            [i.click() for i in self.Waits(css='button[title="Remove item. Shift + click remove button to remove all."]')]
            for index, value in enumerate(["2", "3", "4"]):
                if index:
                    self.Wait(css='button[title="Add item"]')
                select = self.Waits(tag_name="select")
                self.choiceSelect(select[2], value)
                self.logger.info(value)

            textareas = self.Waits(tag_name="textarea")
            textareas[1].send_keys("aa")
            radios = self.Waits(css=".wc-option>input")
            if not "group":
                radios[20].click()
            else:
                radios[21].click()
        elif "否":
            pass

        self.next_page

    # 第三页
    def page_3(self):
        inputs = self.Waits(css='.wc-textfield>input')
        inputs[1].send_keys()

    @property
    def next_page(self):
        self.Wait(css=".wc-east > button")


if __name__ == "__main__":
    r = Australia(no_win=0)
    # r.register
    # r.active()
    r.visa()
